package la.foton.atividade.dao;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;



public abstract class DAOImpl<T, I extends Serializable> implements DAO<T, I> {

	@PersistenceContext
	private EntityManager entityManager;

	@Transactional
	@Override
	public T save(T entity) {

		//T saved = null;		
		//saved = getEntityManager().persist(entity);	
		getEntityManager().persist(entity);

		return entity;
	}
	
	@Transactional
	@Override
	public T update(T entity){
		
		return entityManager.merge(entity);
	}

	@Transactional
	@Override
	public void remove(T entity) {		
		getEntityManager().remove(entity);
	}
	
	@Transactional
	@Override
	public void remove(Class<T> classe, I pk) {		
		getEntityManager().remove(getEntityManager().getReference(classe, pk));
	}

	@Transactional(readOnly=true)
	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll(Class<T> classe) {

      List<T> list = null;
      try
      {
         list = getEntityManager().createQuery(
            "select o from " + classe.getSimpleName() + " o")
                  .getResultList();
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }

      return list;
	}


	@Override
	public EntityManager getEntityManager() {

		return entityManager;
	}

	@Transactional
	@Override
	public T findById(Class<T> classe, I pk) {
		try {
			return getEntityManager().find(classe, pk);
		} catch (NoResultException e) {
			return null;
		}
	}

}
